import { BrowserWindow, app } from "electron";
import { exec, spawn } from "child_process";
import { getExtraFiles } from "../utils.js";
import path from 'path';

const isMac = process.platform === "darwin"; // 获取当前运行平台
export const openDevTool = () => {
  // 当前激活的窗口
  const win = BrowserWindow.getFocusedWindow();
  win.webContents.openDevTools({
    mode: "detach",
  });
};

export const getProcess = () => {
  return JSON.stringify(process);
};

export const isPackaged = () => {
  return app.isPackaged;
};

export const getProcessByExec = () => {
  return new Promise((resolve, reject) => {
    exec("env", {}, (error, stdout, stderr) => {
      if (error) {
        reject(error);
      } else if (stderr) {
        reject(stderr);
      } else {
        resolve(stdout);
      }
    });
  });
};

export const nodeExec = (script) => {
  return new Promise((resolve, reject) => {
    exec(script, {}, (error, stdout, stderr) => {
      let res = {};
      if (error) {
        res = {
          type: "error",
          content: error,
        };
      } else if (stderr) {
        res = {
          type: "stderr",
          content: stderr,
        };
      } else {
        res = {
          type: "stdout",
          content: stdout,
        };
      }
      resolve(res);
    });
  });
};

export const nodeSpawn = (scriptPath) => {
  const win = global.app.mainWindow;
  const arg = ["-ExecutionPolicy", "Bypass", "-File", scriptPath];
  let child = spawn("powershell", arg, { shell: true });
  if (isMac) {
    child = spawn(scriptPath, [], { shell: true });
  }
  
  const sendMsg = (status, output) => {
    const params = {
      id: child.pid,
      type: status,
      content: output,
    };
    console.log(params);
  
    win.webContents.send("processMsg", params);
  };
  
  let finalRes;
  // 捕获标准输出
  child.stdout.on("data", (output) => {
    const outputStr = output.toString();
    sendMsg("stdout", outputStr);
  });

  // 捕获标准错误输出
  child.stderr.on("data", (output) => {
    sendMsg("stderr", output.toString());
  });

  // 当子进程结束时，会触发 'close' 事件
  child.on("close", (output) => {
    sendMsg("close", finalRes);
  });
};

export const spawnTest = async () => {
  const extraFiles = getExtraFiles();
  let scriptPath = path.join(extraFiles, "shell", "test.ps1");
  if (isMac) {
    scriptPath = path.join(extraFiles, "shell", "test.sh");
    await exec("chmod 777 " + scriptPath);
  }
  nodeSpawn(scriptPath);
};
